// WebSocket fallback for IE compatibility
(function() {
    'use strict';
    
    // Check if WebSocket is supported
    if (window.WebSocket) {
        return; // Native WebSocket is available
    }
    
    // IE fallback using long polling
    window.WebSocket = function(url) {
        this.url = url;
        this.readyState = WebSocket.CONNECTING;
        this.onopen = null;
        this.onmessage = null;
        this.onclose = null;
        this.onerror = null;
        
        var self = this;
        var pollInterval = null;
        var isConnected = false;
        
        // Convert WebSocket URL to HTTP URL
        var httpUrl = url.replace('ws://', 'http://').replace('wss://', 'https://');
        
        // Connect function
        this.connect = function() {
            // Try to establish connection
            var xhr = new XMLHttpRequest();
            xhr.open('GET', httpUrl.replace('/ws', '/poll/connect'), true);
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        self.readyState = WebSocket.OPEN;
                        isConnected = true;
                        if (self.onopen) self.onopen();
                        self.startPolling();
                    } else {
                        self.readyState = WebSocket.CLOSED;
                        if (self.onerror) self.onerror(new Error('Connection failed'));
                    }
                }
            };
            xhr.send();
        };
        
        // Start polling for messages
        this.startPolling = function() {
            if (!isConnected) return;
            
            pollInterval = setInterval(function() {
                if (!isConnected) return;
                
                var xhr = new XMLHttpRequest();
                xhr.open('GET', httpUrl.replace('/ws', '/poll/messages'), true);
                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4) {
                        if (xhr.status === 200 && xhr.responseText) {
                            try {
                                var messages = JSON.parse(xhr.responseText);
                                if (messages && messages.length > 0) {
                                    for (var i = 0; i < messages.length; i++) {
                                        if (self.onmessage) {
                                            self.onmessage({
                                                data: JSON.stringify(messages[i])
                                            });
                                        }
                                    }
                                }
                            } catch (e) {
                                console.error('Error parsing poll response:', e);
                            }
                        }
                    }
                };
                xhr.send();
            }, 1000); // Poll every second
        };
        
        // Send message
        this.send = function(data) {
            if (this.readyState !== WebSocket.OPEN) {
                throw new Error('WebSocket is not open');
            }
            
            var xhr = new XMLHttpRequest();
            xhr.open('POST', httpUrl.replace('/ws', '/poll/send'), true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status !== 200) {
                    if (self.onerror) self.onerror(new Error('Send failed'));
                }
            };
            xhr.send(data);
        };
        
        // Close connection
        this.close = function() {
            isConnected = false;
            this.readyState = WebSocket.CLOSED;
            if (pollInterval) {
                clearInterval(pollInterval);
                pollInterval = null;
            }
            if (this.onclose) this.onclose();
        };
        
        // Auto-connect
        setTimeout(function() {
            self.connect();
        }, 0);
    };
    
    // WebSocket constants
    WebSocket.CONNECTING = 0;
    WebSocket.OPEN = 1;
    WebSocket.CLOSING = 2;
    WebSocket.CLOSED = 3;
})();

// JSON2 fallback for IE7/8
if (!window.JSON) {
    window.JSON = {
        parse: function(str) {
            return eval('(' + str + ')');
        },
        stringify: function(obj) {
            var t = typeof obj;
            if (t !== 'object' || obj === null) {
                if (t === 'string') obj = '"' + obj + '"';
                return String(obj);
            } else {
                var n, v, json = [], arr = obj && obj.constructor === Array;
                for (n in obj) {
                    v = obj[n];
                    t = typeof v;
                    if (t === 'string') v = '"' + v + '"';
                    else if (t === 'object' && v !== null) v = JSON.stringify(v);
                    json.push((arr ? '' : '"' + n + '":') + String(v));
                }
                return (arr ? '[' : '{') + String(json) + (arr ? ']' : '}');
            }
        }
    };
}

// Console fallback for IE
if (!window.console) {
    window.console = {
        log: function() {},
        error: function() {},
        warn: function() {},
        info: function() {}
    };
}

// Array.forEach fallback for IE8
if (!Array.prototype.forEach) {
    Array.prototype.forEach = function(callback, thisArg) {
        var T, k;
        if (this == null) {
            throw new TypeError('this is null or not defined');
        }
        var O = Object(this);
        var len = parseInt(O.length) || 0;
        if (typeof callback !== 'function') {
            throw new TypeError(callback + ' is not a function');
        }
        if (arguments.length > 1) {
            T = thisArg;
        }
        k = 0;
        while (k < len) {
            var kValue;
            if (k in O) {
                kValue = O[k];
                callback.call(T, kValue, k, O);
            }
            k++;
        }
    };
}

// addEventListener fallback for IE8
if (!window.addEventListener) {
    window.addEventListener = function(type, listener, useCapture) {
        window.attachEvent('on' + type, listener);
    };
    
    window.removeEventListener = function(type, listener, useCapture) {
        window.detachEvent('on' + type, listener);
    };
}

// Document ready function
function documentReady(fn) {
    if (document.readyState === 'complete' || document.readyState === 'interactive') {
        setTimeout(fn, 1);
    } else {
        document.addEventListener('DOMContentLoaded', fn);
    }
}

// Export for global use
window.documentReady = documentReady; 